﻿using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
namespace DX
{
    public class JsonSerializeProvider : ISerializeProvider, IBufferSerializeProvider
    {

        public JsonSerializeProvider(IOptions<JsonSerializerSettings> options)
        {
            this.options = options;
        }
        private readonly IOptions<JsonSerializerSettings> options;
        public T Deserialize<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json, options.Value);
        }

        public string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj, options.Value);
        }

        public T Deserialize<T>(byte[] buffer)
        {
            var json = System.Text.Encoding.UTF8.GetString(buffer);
            return JsonConvert.DeserializeObject<T>(json, options.Value);
        }

        byte[] IBufferSerializeProvider.Serialize(object obj)
        {
            var json = JsonConvert.SerializeObject(obj, options.Value);
            return System.Text.Encoding.UTF8.GetBytes(json);
        }
    }
}